package auth

import (
	"admin/dto"
	m "admin/models/auth"
	"admin/utils/pagination"
	"gorm.io/gorm"
)

// OperationLogRepoInterface 操作日志仓库接口
type OperationLogRepoInterface interface {
	Create(log *m.OperationLog) error
	List(req dto.OperationListReq) (*pagination.PageResult[m.OperationLog], error)
	GetByID(id int64) (*m.OperationLog, error)
}

// OperationLogRepo 基于GORM的操作日志仓库实现
type OperationLogRepo struct {
	db *gorm.DB
}

// NewOperationLogRepo 创建基于GORM的操作日志仓库实例
// db: GORM数据库连接
// 返回值: 操作日志仓库实例指针
func NewOperationLogRepo(db *gorm.DB) *OperationLogRepo {
	return &OperationLogRepo{db: db}
}

// Create 创建操作日志
// log: 操作日志对象
// 返回值: 错误信息
func (r *OperationLogRepo) Create(log *m.OperationLog) error {
	return r.db.Create(log).Error
}

// List 获取操作日志列表(分页)
// page: 页码
// pageSize: 每页数量
// 返回值: 操作日志列表、总数和错误信息
func (r *OperationLogRepo) List(req dto.OperationListReq) (*pagination.PageResult[m.OperationLog], error) {
	db := r.db.Model(&m.OperationLog{})
	if req.Keyword != "" {
		db = db.Where("username LIKE ? OR path LIKE ?", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}
	return pagination.Paginate[m.OperationLog](db, req.PageInfo, &[]m.OperationLog{})
}

// GetByID 根据ID获取操作日志详细信息
// id: 操作日志ID
// 返回值: 操作日志对象和错误信息
func (r *OperationLogRepo) GetByID(id int64) (*m.OperationLog, error) {
	var log m.OperationLog
	err := r.db.First(&log, id).Error
	return &log, err
}
